package com.xfgg.cloud.boot.config.mysql;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 多数据源配置
 *
 * @author xfgg
 */
@Configuration
@MapperScan(basePackages = "com.xfgg.cloud.domain.repository.mapper.admin", sqlSessionFactoryRef = "AdminSessionFactory")
public class AdminDataSourceConfig {
    @Bean(name = "adminDataSource")
    @Qualifier("adminDataSource")
    public DataSource adminDataSource(@Value("${spring.datasource.admin.driver-class-name}") String driver,
                                      @Value("${spring.datasource.admin.url}") String url,
                                      @Value("${spring.datasource.admin.username}") String userName,
                                      @Value("${spring.datasource.admin.password}") String passWord) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }

    @Bean(name = "AdminSessionFactory")
    @Primary
    public SqlSessionFactory adminSessionFactory(@Qualifier("adminDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "adminSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("adminDataSource") DataSource dataSource) throws Exception {
        return new SqlSessionTemplate(adminSessionFactory(dataSource));
    }

    @Bean(name = "adminTransactionManager")
    @Primary
    public DataSourceTransactionManager adminTransactionManager(@Qualifier("adminDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
